package com.hw.netty;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

@Sharable
public class NettyServerHandler extends ChannelInboundHandlerAdapter{
	
	@Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
//		编码并发送数据
		ctx.writeAndFlush(Unpooled.copiedBuffer("Netty Server",CharsetUtil.UTF_8));
    }
	
	@Override
	public void channelRead(ChannelHandlerContext ctx,Object msg) {
//		自动解码并接受数据
		ByteBuf buf=(ByteBuf)msg;
		System.out.println("server recived:"+buf.toString(CharsetUtil.UTF_8));
	}
	
	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) {
		ctx.writeAndFlush(Unpooled.EMPTY_BUFFER)
		.addListener(ChannelFutureListener.CLOSE);
	}

	@Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		cause.printStackTrace();
		ctx.close();
    }
}
